﻿using System.Collections.Generic;
using UnityEditor;
using UnityEditor.AddressableAssets.Build;
using UnityEditor.AddressableAssets.Settings;
using UnityEngine;

public class AnalyzeRuleAddressEqualPath : UnityEditor.AddressableAssets.Build.AnalyzeRules.AnalyzeRule
{
    public override bool CanFix
    {
        get { return true; }
        set { }
    }

    public override string ruleName
    {
        get { return "AddressEqualAssetPath"; }
    }

    [SerializeField]
    List<AddressableAssetEntry> m_MisnamedEntries = new List<AddressableAssetEntry>();
    [SerializeField]
    public override List<AnalyzeResult> RefreshAnalysis(AddressableAssetSettings settings)
    {
        List<AnalyzeResult> results = new List<AnalyzeResult>();
        AddressableAssetGroup group = settings.FindGroup(this.OnGetGroupName());

        foreach (var e in group.entries)
        {
            OnRefreshAnalysis(group, e, results);
        }

        if (results.Count == 0)
            results.Add(new AnalyzeResult { resultName = "No issues found." });

        return results;
    }

    protected virtual void OnRefreshAnalysis(AddressableAssetGroup group, AddressableAssetEntry e, List<AnalyzeResult> results)
    {
        if (/*e.address.Contains("Assets") && e.address.Contains("/") && */e.address != e.AssetPath)
        {
            m_MisnamedEntries.Add(e);
            results.Add(new AnalyzeResult { resultName = group.Name + kDelimiter + e.address + "<>" + e.AssetPath, severity = MessageType.Error });
        }
    }

    protected virtual string OnGetGroupName()
    {
        return AddressablesConfig.UIGroup;
    }

    public override void FixIssues(AddressableAssetSettings settings)
    {
        foreach (var e in m_MisnamedEntries)
        {
            e.address = e.AssetPath;
        }
        m_MisnamedEntries = new List<AddressableAssetEntry>();
    }

    public override void ClearAnalysis()
    {
        m_MisnamedEntries = new List<AddressableAssetEntry>();
    }
}


//[InitializeOnLoad]
//class RegisterAnalyzeRuleAddressEqualPath
//{
//    static RegisterAnalyzeRuleAddressEqualPath()
//    {
//        AnalyzeSystem.RegisterNewRule<AnalyzeRuleAddressEqualPath>();
//    }
//}
